
module.exports = class extends think.cmswing.ws {
  // 构造方法
  constructor(ctx) {
    super(ctx);
  }
  async __before() {
    await super.__before();
  }
  indexAction() {
    const data = {};
    data.userActive = {
      '描述': '注册通过后回写',
      '接收参数': 'user对象的若干属性',
      '返回参数': 'errno 错误码；errmsg 错误信息；data 返回数据；'
    };
    return this.json(data);
  }

  // 测试用请求
  async testAction() {
    const tjname = '雷';
    const resdatary = await this.requestOA('executeQuery', { sql: `select id from hrmresource where lastname='${tjname}'` });
    if (resdatary && resdatary.errno == 0) {
      console.log('resdatary.data.list=' + resdatary.data.list);
      if (think.isEmpty(resdatary.data.list)) {
        console.log('1111111111111.data.list=' + resdatary.data.list);
      }
    }

    return this.success(resdatary, '查询成功');
  }
  // 行情查询
  async hangqingAction() {
    const cid = this.get('id');
    const id = await this.model('category').where({ pid: 133 }).getField('id');
    console.log('id=' + id);
    const map = {};
    if (!cid) {
      map.cid = ['IN', id];
    } else {
      map.cid = cid;
    }
    const data = await this.model('category_sp').where(map).select();
    if (!data) { return this.fail('查询失败') }
    return this.success(data, '查询成功');
  }

  async areaAction() {
    const res = await this.model('area').select();
    return this.success(res, '查询成功');
  }

  async materialAction() {
    const material = this.model('material');
    const res = await material.field('id,label,pid').select({where: {status: 1}});
    return this.success(arr_to_tree(res, 0, {label: '全部'}), '查询成功');
  }

  async sendsmsAction() {
    const mobile = this.post('mobile');
    console.log(mobile);
    const sysnumber = Math.random() * 900000 | 100000;
    const SMSClient = require('@alicloud/sms-sdk');
    // ACCESS_KEY_ID/ACCESS_KEY_SECRET 根据实际申请的账号信息进行替换
    const accessKeyId = 'LTAIP8HnmPaFrJpl';
    const secretAccessKey = 'NrHIww6TNfvaX9dz22BRESXFTTO8Pl';
    // const queueName = 'Alicom-Queue-1092397003988387-';
    const smsClient = new SMSClient({ accessKeyId, secretAccessKey });
    // 发送短信
    smsClient.sendSMS({
      PhoneNumbers: mobile,
      SignName: '葛再生',
      TemplateCode: 'SMS_152471607',
      TemplateParam: '{"code":"' + sysnumber + '"}'
    }).then(function(res) {
      const { Code } = res;
      if (Code === 'OK') {
        // 处理返回参数
        console.log(res);
      }
    }, function(err) {
      console.log(err);
    });
  }

  async querysmsAction() {
    const mobile = this.get('mobile') || this.post('mobile');
    const sysnumber = this.get('sysnumber') || this.post('sysnumber');
    const date = JSON.stringify(new Date()).substring(1, 5) + JSON.stringify(new Date()).substring(6, 8) + JSON.stringify(new Date()).substring(9, 11);
    console.log('date=' + date);
    const SMSClient = require('@alicloud/sms-sdk');
    // ACCESS_KEY_ID/ACCESS_KEY_SECRET 根据实际申请的账号信息进行替换
    const accessKeyId = 'LTAIP8HnmPaFrJpl';
    const secretAccessKey = 'NrHIww6TNfvaX9dz22BRESXFTTO8Pl';
    // const queueName = 'Alicom-Queue-1092397003988387-';
    const smsClient = new SMSClient({ accessKeyId, secretAccessKey });
    let content = null;
    const self = this;
    // 查询短信发送详情
    console.log(1);
    await smsClient.queryDetail({
      PhoneNumber: mobile,
      SendDate: date,
      PageSize: '10',
      CurrentPage: '1'
    }).then(async(res) => {
      const { Code, SmsSendDetailDTOs } = res;
      if (Code === 'OK') {
        // 处理发送详情内容
        if (SmsSendDetailDTOs.SmsSendDetailDTO.length < 1) {
          return self.fail('验证码错误');
        }
        content = SmsSendDetailDTOs.SmsSendDetailDTO[0].Content.substring(8, 14);
        console.log('+++++content1111=' + content);
        if (sysnumber == content) {
          const user = await this.model('member').where({ username: mobile }).find();
          if (user.id > 0) {
            const userInfo = {
              ...user,
              'uid': user.id,
              'last_login_time': new Date().valueOf(),
              'last_login_ip': _ip2int(this.ip)
            };
            await this.session('webuser', userInfo);
          }
          return self.success({ name: '验证码登陆成功' }, '匹配成功');
        } else {
          return self.fail('验证码错误');
        }
      }
    }, function(err) {
      // 处理错误
      console.log(err);
    });
  }

  // 资质认证添加org_type表示个体或企业
  async addzzshAction() {
    const id = this.post('id');
    const biaoshi = this.post('biaoshi');
    const username = this.post('username');
    const user_code = this.post('user_code');
    const sfzzmpicid = this.post('sfzzmpic');
    const sfzfmpicid = this.post('sfzfmpic');
    const gsmc = this.post('gsmc');
    const yyzzpicid = this.post('yyzzpic');
    const khxkzpicid = this.post('khxkzpic');
    const update_time = new Date().valueOf();
    let sfzzmpic;
    let sfzfmpic;
    let yyzzpic;
    let khxkzpic;
    if (sfzzmpicid) {
      console.log('sfzzmpicid=' + sfzzmpicid);
      sfzzmpic = await this.model('ext_attachment_pic').where({ id: sfzzmpicid }).getField('path');
      console.log('sfzzmpic=' + sfzzmpic);
    }
    if (sfzfmpicid) {
      console.log('sfzfmpicid=' + sfzfmpicid);
      sfzfmpic = await this.model('ext_attachment_pic').where({ id: sfzfmpicid }).getField('path');
    }
    if (yyzzpicid) {
      console.log('yyzzpicid=' + yyzzpicid);
      yyzzpic = await this.model('ext_attachment_pic').where({ id: yyzzpicid }).getField('path');
    }
    if (khxkzpicid) {
      console.log('khxkzpicid=' + khxkzpicid);
      khxkzpic = await this.model('ext_attachment_pic').where({ id: khxkzpicid }).getField('path');
    }
    let res;
    if (biaoshi == 0) {
      res = await this.model('member').where({ id: id }).update({
        update_time: update_time,
        org_type: 0,
        zhucestatus: 1,
        gsmc: username,
        real_name: username,
        user_code: user_code,
        sfzzmpic: JSON.stringify(sfzzmpic),
        sfzfmpic: JSON.stringify(sfzfmpic)
      });
      console.log('res=' + res);
    } else if (biaoshi == 1) {
      res = await this.model('member').where({ id: id }).update({
        update_time: update_time,
        org_type: 1,
        zhucestatus: 1,
        real_name: username,
        user_code: user_code,
        sfzzmpic: JSON.stringify(sfzzmpic),
        sfzfmpic: JSON.stringify(sfzfmpic),
        gsmc: gsmc,
        yyzzpic: JSON.stringify(yyzzpic)
      });
    } else if (biaoshi == 2) {
      res = await this.model('member').where({ id: id }).update({
        update_time: update_time,
        org_type: 1,
        zhucestatus: 1,
        real_name: username,
        user_code: user_code,
        sfzzmpic: JSON.stringify(sfzzmpic),
        sfzfmpic: JSON.stringify(sfzfmpic),
        gsmc: gsmc,
        yyzzpic: JSON.stringify(yyzzpic),
        khxkzpic: JSON.stringify(khxkzpic)
      });
    }

    if (res) {
      const list = await this.model('member').where({ id: id }).find();
      return this.success(list, '用户资质新增成功');
    } else {
      return this.fail('用户资质新增失败');
    }
  }
  // 通过id或mobile查询人员信息
  async chaxunrenyuanAction() {
    const id = this.get('id');
    const mobile = this.get('mobile');
    if (id) {
      const res = await this.model('member').where({ id: id }).find();
      if (!res) { return this.fail('查无此人') }
      return this.success(res, '查询成功');
    }
    if (mobile) {
      const res = await this.model('member').where({ mobile: mobile }).find();
      if (!res) { return this.fail('查无此人') }
      return this.success(res, '查询成功');
    }
    return this.fail('参数传递错误');
  }
  // 确认订单按钮
  async orderquerenAction() {
    const id = this.post('id');
    const user_id = this.post('user_id');
    const data = await this.model('order').where({ id: id }).find();
    let res;
    if (user_id == data.gongid) {
      res = await this.model('order').where({ id: id, gongid: user_id }).update({ gongqueren: 1 });
    }
    if (user_id == data.xuid) {
      res = await this.model('order').where({ id: id, xuid: user_id }).update({ xuqueren: 1 });
    }

    if (!res) {
      return this.fail('确认失败');
    }
    return this.success(res, '确认成功');
  }
  // 订单取消
  async orderquxiaoAction() {
    const id = this.post('id');
    const user_id = this.post('user_id');
    const data = await this.model('order').where({ id: id }).find();
    let res;
    if (user_id == data.gongid) {
      res = await this.model('order').where({ id: id, gongid: user_id }).update({ gongqueren: 2 });
    }
    if (user_id == data.xuid) {
      res = await this.model('order').where({ id: id, xuid: user_id }).update({ xuqueren: 2 });
    }
    // TODO 等app 更新 要删掉
    if (!res) {
      res = await this.model('order').where({ id: id }).update({ gongqueren: 2, xuqueren: 2 });
    }
    //
    if (!res) {
      return this.fail('取消失败');
    }
    return this.success(res, '取消成功');
  }

  async consultAction() {
    const id = this.get('id');
    const fabuid = this.get('fabuid');
    if (!id || !fabuid) { return this.fail('传值异常') }
    const memberinfo = await this.model('member').where({ id: id }).find();
    const gongxuinfo = await this.model('gongxufabu').where({ id: fabuid }).find();
    const dataAll = {
      model: 8,
      uid: id,
      real_name: memberinfo.real_name,
      usermobile: memberinfo.mobile,
      usergsmc: memberinfo.gsmc,
      xinxibiaoti: gongxuinfo.xinxibiaoti,
      gongxuid: fabuid,
      title: '我要了解',
      time: new Date().getTime()
    };
    const id2 = await this.model('consult').add(dataAll);
    if (!id2) return this.fail('后台新增失败');
    return this.success('提问成功');
  }

  // 挂单确认和取消
  async appjiedanAction() {
    const id = this.post('id');
    const userid = this.post('userid');
    const queren = this.post('queren');
    if (id) {
      const gongxuInfo = await this.model('gongxufabu').where({ id: id }).find();
      if (think.isEmpty(gongxuInfo)) {
        think.logger.info('appjiedanAction:供需信息为空:', gongxuInfo);
        return this.fail('确认失败');
      }
      if (queren == 0) {
        const res = await this.model('gongxufabu').where({ id: id }).update({ status: 4 });
        if (!res) { return this.fail('确认失败') }
        if (gongxuInfo.mokuaibiaoshi != 0) {
          // 生成订单
          const order_id = await this.model('cmswing/order').gongtoorder(id, userid);
          if (!order_id) { return this.fail('订单生成失败') }
        }
        const data = await this.model('gongxufabu').where({ id: id }).find();
        return this.success(data, '确认成功');
      } else if (queren == 1) {
        const remarkData = {};
        remarkData.status = 2;
        remarkData.operation = '拒绝接单';
        remarkData.remark_type = 'pages/mine/myMessageDetail';
        remarkData.remark_time = new Date().getTime();
        remarkData.remark_name = userid;
        remarkData.foreign_key = id;
        remarkData.model_name = 'gongxufabu';
        remarkData.operation_value = '{"status":2}';
        const remarksId = await this.model('cmswing/remarks').add(remarkData);
        const updateData = { status: 2, recipient_remarks_id: remarksId };
        const res = await this.model('gongxufabu').where({ id: id }).update(updateData);
        if (!res) { return this.fail('取消失败') }
        const data = await this.model('gongxufabu').where({ id: id }).find();
        return this.success(data, '取消成功');
      }
      return this.fail('参数传递错误');
    }
    return this.fail('参数传递错误');
  }

  // app首页搜索
  async sousuoAction() {
    const query = this.get('query');
    const map = {};
    map.status = 5;
    if (!think.isEmpty(query)) {
      map['xinxibiaoti|leirongmiaoshu|shangpingleibie|diqu'] = ['like', '%' + query + '%'];
      const data = await this.model('gongxufabu').where(map).order('id DESC').page(this.para('page') || 1, 10).select();
      return this.success(data, '查询成功！');
    } else {
      return this.fail('请输入查询条件！');
    }
  }
  // 挂单撤销取消
  async gongxufabucancelAction() {
    const id = this.post('id');
    const userid = this.post('userid');
    const gongxuInfo = await this.model('gongxufabu').where({id: id, status: 0, faburen: userid}).find();
    if (think.isEmpty(gongxuInfo)) {
      think.logger.info('gongxufabucancelAction:供需信息为空:id', id);
      return this.fail('撤销失败');
    }
    const remarkData = {};
    remarkData.status = 6;
    remarkData.operation = '撤销';
    remarkData.remark_contents = '用户app端撤销挂单';
    remarkData.remark_type = 'pages/mine/myIssueDetail';
    remarkData.remark_time = new Date().getTime();
    remarkData.remark_name = userid;
    remarkData.foreign_key = id;
    remarkData.model_name = 'gongxufabu';
    remarkData.operation_value = '{"status":6}';
    const remarksId = await this.model('cmswing/remarks').add(remarkData);
    const updateData = { status: 6, faburen_remarks_id: remarksId };
    const res = await this.model('gongxufabu').where({id: id}).update(updateData);
    if (!res) { return this.fail('撤销失败') }
    return this.success(res, '撤销成功');
  }
  // 挂单下架
  async gongxufabuxiajiaAction() {
    const id = this.post('id');
    const userid = this.post('userid');
    const gongxuInfo = await this.model('gongxufabu').where({id: id, status: 5, faburen: userid}).find();
    if (think.isEmpty(gongxuInfo)) {
      think.logger.info('gongxufabucancelAction:供需信息为空:id', id);
      return this.fail('撤销失败');
    }
    const remarkData = {};
    remarkData.status = 6;
    remarkData.operation = '下架';
    remarkData.remark_contents = '用户app端下架挂单';
    remarkData.remark_type = 'pages/mine/myIssueDetail';
    remarkData.remark_time = new Date().getTime();
    remarkData.remark_name = userid;
    remarkData.foreign_key = id;
    remarkData.model_name = 'gongxufabu';
    remarkData.operation_value = '{"status":6}';
    const remarksId = await this.model('cmswing/remarks').add(remarkData);
    const updateData = { status: 6, offsale_remarks_id: remarksId, offsale_time: remarkData.remark_time };
    const res = await this.model('gongxufabu').where({id: id}).update(updateData);
    if (!res) { return this.fail('撤销失败') }
    return this.success(res, '撤销成功');
  }
};
